package com.tgy.shiroboot.controller;

import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/***
 * @ClassName: index
 * @Description:
 * @Auther: 送一一块二向箔
 * @Date: 20:14 2022/1/5
 * @version : V1.0
 */
@Controller
public class IndexController {

    @RequestMapping({"/","/index"})
    public String aa(Model model){
        model.addAttribute("msg","hello shiro");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add(){
        return "/user/add";
    }
    @RequestMapping("/user/upd")
    public String upd(){
        return "/user/upd";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("login")
    public String toLogin(String username,String password,Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);//执行登录，不报错就成功
            model.addAttribute("msg","登录成功");
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","用户名错误"+e.getMessage());
            return "index";
        }catch (IncorrectCredentialsException e) {
            model.addAttribute("msg","密码错误"+e.getMessage());
            return "index";
        }
    }

}
